//
//  TTTabBar.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/22.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit

protocol TabBarDelegate: NSObjectProtocol {
    
    func turnToANewController()
}

class TTTabBar: UITabBar {
    
    weak var TTDelegate: TabBarDelegate?

    //MARK:
    //MARK: -- 懒加载控件,使用闭包
    private lazy var centerBtn: UIButton = {
        
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .highlighted)
        
        button.sizeToFit()
        
        //添加点击事件
        button.addTarget(self, action: #selector(clickTabBarCenterButton), for: .touchUpInside)
        
        return button
    }()
    
    
    //MARK:
    //MARK: -- 中间按钮点击方法
    func clickTabBarCenterButton(){
        
        //发送tabbar控制器跳转控制器
        TTDelegate?.turnToANewController()
        
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加
        
        setupUI()
    }
    
    //MARK:
    //MARK: -- 界面设置
    func setupUI(){
        
        //添加tabbar中间按钮
        addSubview(centerBtn)
        
        
    }
    
    //MARK:
    //MARK: -- 控件布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        centerBtn.center.x = frame.size.width * 0.5
        centerBtn.center.y = frame.size.height * 0.5
        
        //5个按钮平分宽度
        let btnWidth = frame.size.width/5
        
        //布局自定义tabbar中默认的四个按钮
        //遍历子view
        //自己制作索引
        var index = 0
        for subView in self.subviews{
            //UITabBarButton
            //判断子view的类与某类是否相同
            if(subView.isKind(of: NSClassFromString("UITabBarButton")!)){
                
                //重新布局四个按钮
                subView.frame.origin.x = btnWidth * CGFloat(index)
                
                index += 1
                
                if(index == 2){
                    index += 1
                }
                
            }
        }
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
